package com.github.sbb.sherry.repository;

import com.github.sbb.sherry.common.collect.CollectionUtil;
import com.github.sbb.sherry.repository.entity.Datasource;
import com.github.sbb.sherry.repository.entity.DatasourceExample;
import com.github.sbb.sherry.repository.enums.DatasourceStatusEnum;
import com.github.sbb.sherry.repository.enums.DeleteFlagEnum;
import com.github.sbb.sherry.repository.mapper.DatasourceMapper;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class DatasourceRepository {

  @Resource
  private DatasourceMapper mapper;

  public List<Datasource> getAll() {
    return mapper.selectByExample(null);
  }

  public Datasource getByName(String name) {
    DatasourceExample example = new DatasourceExample();
    example.createCriteria().andNameEqualTo(name);
    return CollectionUtil.getFirstElseNull(mapper.selectByExample(example));
  }

  public long countByName(String name) {
    DatasourceExample example = new DatasourceExample();
    example.createCriteria().andNameEqualTo(name);
    return mapper.countByExample(example);
  }

  public void addDatasource(Datasource datasource) {
    mapper.insertSelective(datasource);
  }

  public List<Datasource> getActiveDatasource() {
    DatasourceExample example = new DatasourceExample();
    example.createCriteria()
        .andStatusEqualTo(DatasourceStatusEnum.ACTIVE.getValue())
        .andDeleteFlagEqualTo(DeleteFlagEnum.NOT_DELETED.getValue());
    return mapper.selectByExample(example);
  }

  public List<Datasource> getActiveDatasourceByType(int type) {
    DatasourceExample example = new DatasourceExample();
    example.createCriteria()
        .andTypeEqualTo((byte) type)
        .andStatusEqualTo(DatasourceStatusEnum.ACTIVE.getValue())
        .andDeleteFlagEqualTo(DeleteFlagEnum.NOT_DELETED.getValue());
    return mapper.selectByExample(example);
  }
}
